package com.gec.controller;

import com.gec.domain.Notify;
import com.gec.domain.PageBean;
import com.gec.domain.PageParam;
import com.gec.domain.User;
import com.gec.service.abst.NotifyService;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

@Controller
@RequestMapping("/Notify")
public class NotifyController extends BaseController {
    private final NotifyService notifyService;
    String dir = "d:\\TTT\\";

    public NotifyController(NotifyService notifyService) {
        this.notifyService = notifyService;
    }

    @RequestMapping("/viewList")
    public String viewList() {
        return "notify/notifyList";
    }

    @RequestMapping(value = "/jsonList",
            produces = "text/html;charset=UTF-8"
    )
    @ResponseBody
    public String jsonList(HttpServletRequest req) {
        // {1}获取分页参数对象
        PageParam param = PageParam.getPageParam(req);
        // {2}调用 service 获取PageBean
        PageBean pBean = null;
        try {
            pBean = notifyService.getNotifyList(param);
            return pBean.toJSON();
        } catch (Exception e) {
            e.printStackTrace();
            return sendError(e.getMessage());
        }
    }


    @RequestMapping("/viewAdd")
    public String viewAdd() {
        return "notify/addNotify";
    }


    @RequestMapping(value = "/saveNotify",
            produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String saveNotify(
            @RequestParam("pdfFile") MultipartFile file,
            @RequestParam("note") String note, HttpServletRequest req) {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        System.out.println(user);
        System.out.println("+----------------------------------------------_+");
        //{1}获取到 上传的文件名.
        String fName = file.getOriginalFilename();
        int size = (int) file.getSize();
        File newFile = new File(dir + fName);
        String notifyName = req.getParameter("notifyName");
        System.out.println(notifyName);
        System.out.println("文件名称:" + fName);
        System.out.println("文件大小:" + size);
        System.out.println("文件备注:" + note);
        Notify notify = new Notify();
        notify.setNotifyName(notifyName);
        notify.setFileName(fName);
        notify.setUploader(user.getNickName());
        notify.setFileSize(size);
        notify.setNote(note);
        try {
            file.transferTo(newFile);
            System.out.println("文件上传成功了.");
            System.out.println("保存到:" + newFile.getAbsolutePath());
            notifyService.saveNotify(notify);
            return sendData("上传文件成功");
        } catch (Exception e) {
            e.printStackTrace();
            return sendError(e.getMessage());
        }
    }


    String baseDir = "D:\\ttt\\";

    @RequestMapping(value = "/downNotify",
            produces = "text/html;charset=utf-8")
    @ResponseBody
    public void downNotify(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // [a]设置正文 mime 类型
        resp.setContentType("application/x-msdownload");
        // 获取文件名
        String id = req.getParameter("id");
        Notify notify = notifyService.getNotifyById(id);
        String fileName = notify.getFileName();
        // [b]添加响应头部
        String encName = URLEncoder.encode(fileName, "UTF-8");
        String val = "attachment;filename=\"" + encName + "\"";
        resp.addHeader("Content-Disposition", val);
        // [c]设置正文的内容大小。【pdf大小】
        File file = new File(baseDir + fileName);
        int size = (int) file.length();
        resp.setContentLength(size);
        String path = baseDir + fileName;
        System.out.println(path);
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(path);
            byte[] buff = new byte[8192];
            int cnt = 0;
            // {1}获取 resp 的输出流对象。
            OutputStream os = resp.getOutputStream();
            while (fis.available() > 0) {
                cnt = fis.read(buff);
                // {2}写入到输出流中。
                os.write(buff, 0, cnt);
            }
            Integer count = notify.getDownTimes();
            System.out.println("下载次数:" + count);
            notify.setDownTimes(++count);
            notifyService.downNotifyCount(notify);
        } finally {
            fis.close(); // 关闭输入流对象
        }
    }

    @RequestMapping("/getNotify")
    public String getNotify(@Param("id") String id) {
        System.out.println("=__----------------");
        System.out.println(id);
        Notify notify = null;
        try {
            notify = notifyService.getNotifyById(id);
            return sendData(notify);
        } catch (Exception e) {
            e.printStackTrace();
            return sendError(e.getMessage());
        }
    }

    @RequestMapping(value = "/editNotify",
            produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String editNotify(HttpServletRequest req) {
        // {1}拿到表单传来的数据 ---> User 对象。

        // {2}调用 service 的方法[新增 / 更新]。
        try {
            Notify notify = getBean(req, Notify.class);
            //            String notifyName = req.getParameter("notifyName");
            //            notify.setNotifyName(notifyName);
            notifyService.updateNotitf(notify);
            // {4}返回数据给前端。
            return sendSuccess();
        } catch (Exception e) {
            // {3}异常数据处理 [发送给前端页面]
            e.printStackTrace();
            return sendError(e.getMessage());
        }

    }

    @RequestMapping("/delNotify")
    @ResponseBody
    public String delNotify(@RequestParam("id") String id) {
        System.out.println(id);
        try {
            notifyService.delNotify(id);
            return sendData(id);
        } catch (Exception e) {
            e.printStackTrace();
            return sendError(e.getMessage());
        }

    }

}
